<template>
  <div>
    <Row :gutter="10">
      <Col :span="4">
        <div class="card-container scroll-container">
          <p>固件版本ID</p>
          <span>{{ upgradeInfo.code }}</span>
          <p class="mt-2">固件包版本</p>
          <span>{{ `${upgradeInfo.version}` }}</span>

          <p class="mt-2">更新类型</p>
          <span>{{ appUpdateTypeEnum[upgradeInfo.updateType] }}</span>
          <div class="info-item">
            <p class="mt-2">设备类型/型号</p>
            <Tree
              v-if="push.modelAlwaysVOS && push.modelAlwaysVOS.length"
              :tree-data="push.modelAlwaysVOS"
              :field-names="fileNames"
            />
          </div>
          <div v-if="upgradeInfo.updateType == '2'">
            <p class="mt-2">待升级固件版本</p>
            <span>{{ `${upgradeInfo.allowVersion}` }}</span>
          </div>
          <p class="mt-2">版本说明</p>
          <span>{{ upgradeInfo.versionDesc }}</span>
          <p class="mt-2">上传地址</p>
          <span>{{ upgradeInfo.versionDowmloadUrl }}</span>
          <p class="mt-2">是否启用</p>
          <Tag :color="upgradeInfo.isEnable == '0' ? 'green' : 'red'">{{
            upgradeInfo.isEnable == '0' ? '启用' : '停用'
          }}</Tag>
          <p class="mt-2">创建时间</p>
          <span>{{ upgradeInfo.createTime }}</span>
        </div>
      </Col>
      <Col :span="20">
        <div class="card-container">
          <Row>
            <Col :span="6">
              <p>项目总数</p>
              <span>{{ statistics.projectNum }}</span></Col
            >
            <Col :span="3">
              <p>已选设备总数</p>
              <span>{{ dataSource.length }}</span></Col
            >
            <Col :span="3" v-for="(item, index) in statistics.typeList">
              <p>{{ item.typeName }}</p>
              <span>{{ item.sum }}</span>
            </Col>
          </Row>
        </div>
        <Row justify="space-between" class="mt-2">
          <Col>
            <div class="table-title">推送列表</div>
          </Col>
          <Col>
            <Space>
              <b-button icon="add" @click="onSelect()">选择设备</b-button>
              <b-button v-if="!multiple" icon="delete" @click="onClear()"
                >移除设备</b-button
              >
            </Space>
          </Col>
        </Row>
        <div class="verification_table">
          <Table
            row-key="deviceCode"
            class="device_table"
            :scroll="{ x: 500, y: scrollHeight }"
            :columns="columns"
            size="middle"
            :data-source="dataSource"
            :row-selection="rowSelection"
          >
          </Table>
        </div>
      </Col>
    </Row>
  </div>
  <Modal
    v-model:open="openDevice"
    title="选择设备"
    :width="1200"
    :mask-closable="false"
    centered
    :footer="null"
    destroyOnClose
  >
    <Device
      :row="upgradeInfo"
      :deviceData="deviceData"
      @pushData="updataData"
    ></Device>
  </Modal>
</template>
<script setup lang="tsx">
import { computed, onMounted, reactive, ref } from 'vue';
import {
  Col,
  Modal,
  Row,
  Space,
  Table,
  type TableProps,
  Tag,
  Tree,
  TreeProps,
  message,
} from 'ant-design-vue';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { columnWidth, listToEnum } from '@/utils/utils';
import { appUpdateTypeEnum } from '@/constant/push';
import { fetchDictsOfType } from '@/api/dict';
import {
  firmclickPush,
  firmpushProject,
  getDeviceMode,
  getFirmwareInfo,
  getModelStatistics,
} from '@/api/push';
import Device from './Device.vue';

const statistics = ref({
  projectNum: 0,
  typeList: [
    {
      typeName: '预警终端',
      sum: 0,
    },
    {
      typeName: '预警喇叭',
      sum: 0,
    },
    {
      typeName: '桌面终端',
      sum: 0,
    },
  ],
});

const props = defineProps({
  push: {
    type: Object,
    default: {},
  },
});

interface TableRecord {
  deviceCode: string;
  deviceId: string;
  [key: string]: any;
}
const upgradeInfo = props.push;

const fileNames: TreeProps['fieldNames'] = {
  title: 'typeName',
  children: 'modeName',
};
const modalList = ref<any[]>([]);
const sysDeviceModeEnum = ref<Record<string, any>>({});
onMounted(() => {
  fetchDictsOfType(['sys_device_mode']).then((res: any) => {
    const { sys_device_mode } = res.data;
    sysDeviceModeEnum.value = listToEnum(
      sys_device_mode,
      'dictValue',
      'dictLabel',
    );
  });
  getFirmwareInfo(props.push.versionId).then((res) => {
    upgradeInfo.versionDowmloadUrl = (res as any).data.versionDowmloadUrl;
  });
  getDeviceMode({}).then((res) => {
    modalList.value = res.data as any;
  });
});
const formatModal = (val: any) => {
  let arr = modalList.value.filter((item) => {
    return item.modelId == val;
  });
  return arr[0]?.model;
};
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectedRow.value.map((row) => row.deviceCode), // Extract deviceCode for selectedRowKeys
    onChange: (
      selectedRowKeys: (string | number)[],
      selectedRows: TableRecord[],
    ) => {
      handlePushSelection(selectedRowKeys as string[], selectedRows);
    },
    getCheckboxProps: (record: TableRecord) => ({
      deviceCode: record.deviceCode,
      disabled: false,
    }),
  };
});
const multiple = ref(true);
const selectedRow = ref<TableRecord[]>([]);
const handlePushSelection = (keys: string[], rows: TableRecord[]) => {
  selectedRow.value = rows;
  multiple.value = !rows.length;
};
const dataSource = ref<any[]>([]);
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '所属项目',
    dataIndex: 'shortName',
    align: 'center',
    width: columnWidth('shortName', dataSource.value, '所属项目'),
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    align: 'center',
    width: columnWidth('deviceCode', dataSource.value, '所属项目'),
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    align: 'center',
    customRender({ text, record }) {
      return text + (record.versionCode ? `(${record.versionCode})` : '');
    },
    width: columnWidth('softwareVersion', dataSource.value, '所属项目', 20),
  },
  {
    title: '固件版本',
    dataIndex: 'firmwareVersion',
    align: 'center',
    width: columnWidth('firmwareVersion', dataSource.value, '所属项目'),
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    align: 'center',
    customRender({ text }) {
      return formatModal(text);
    },
    width: columnWidth('modelId', dataSource.value, '所属项目', 20),
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    align: 'center',
    width: columnWidth('deviceType', dataSource.value, '所属项目'),
    customRender({ text }) {
      return sysDeviceModeEnum.value[text as string];
    },
  },
  {
    title: '地址',
    dataIndex: 'address',
    align: 'center',
    width: columnWidth('address', dataSource.value, '所属项目'),
  },
]);

const deviceData = ref<any[]>([]);
const openDevice = ref(false);
const onSelect = () => {
  deviceData.value = JSON.parse(JSON.stringify(dataSource.value));
  openDevice.value = true;
};

const getDeviceStatistics = (list: any) => {
  console.log(list);
  let _arr = list.map((item) => {
    return item.deviceId;
  });
  getModelStatistics(_arr.join(',')).then((res) => {
    console.log(res, 'res');
    statistics.value = res.data as any;
  });
};
const updataData = (data: any) => {
  dataSource.value = data;
  getDeviceStatistics(dataSource.value);
};

const onClear = () => {
  for (let i = 0; i < selectedRow.value.length; i++) {
    for (let j = 0; j < dataSource.value.length; j++) {
      if (
        selectedRow.value[i].deviceCode === dataSource.value[j].deviceCode &&
        selectedRow.value[i].deviceId === dataSource.value[j].deviceId
      ) {
        dataSource.value.splice(j, 1);
      }
    }
  }
  if (rowSelection.value && rowSelection.value.onChange) {
    rowSelection.value.onChange([], []);
  }
};
const emit = defineEmits(['pushUpdate']);
async function submitForm() {
  if (dataSource.value.length == 0)
    return message.error('推送列表不能为空，请选择设备');
  const res = await firmclickPush({
    versionId: props.push.versionId,
    type: '1',
    dataId: props.push.id,
  });

  if (res.code === 200) {
    const list = dataSource.value.map((ele: any) => ({
      versionId: props.push.versionId,
      versionPushTotalId: res.data,
      code: ele.deviceCode,
      deviceId: ele.deviceId,
    }));
    await firmpushProject({ list });
    emit('pushUpdate', {
      versionId: props.push.versionId,
      versionPushTotalId: res.data,
      upgradeStatus: '',
    });
  }
}

const scrollHeight = ref(0);
onMounted(() => {
  const dom = document.querySelector('.device_table');
  scrollHeight.value = dom?.getBoundingClientRect().height - 40 || 0;
});

defineExpose({
  submitForm,
});
</script>
<style lang="scss" scoped>
.scroll-container {
  height: 60vh;
  overflow-y: auto;
  p {
    position: relative;
    color: #fff;
    &::before {
      position: absolute;
      left: -8px;
      top: 50%;
      transform: translateY(-50%);
      content: '';
      width: 2px;
      height: 12px;
      background-color: #1890ff;
    }
  }
}

.table-title {
  height: 36px;
  line-height: 36px;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}
:deep(.ant-tree) {
  background: none;
}
.verification_table {
  :deep(.ant-table) {
    height: calc(60vh - 200px);
  }
  :deep(.ant-table-body) {
    height: calc(60vh - 240px);
  }
}
</style>
